package com.alibaba.bink;

import com.galeno.FlinkUtils;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.fs.FileSystem;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;


/**
 * @author galeno
 * @Title:
 * @Description:
 * @date 2021/10/2722:00
 */
public class WriteSinkDemo {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",9999);
        StreamExecutionEnvironment env = FlinkUtils.getLocEnvWebUI(conf);
        DataStreamSource<String> lines = env.socketTextStream("galeno", 11111);

        SingleOutputStreamOperator<Tuple2<String, Integer>> map = lines.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                return Tuple2.of(value, 1);
            }
        });
//        lines.writeToSocket("192.168.77.101", 22222, new SerializationSchema<String>() {
//            @Override
//            public byte[] serialize(String element) {
//                return element.getBytes();
//            }
//        });
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = map.keyBy(x -> x.f0);
        SingleOutputStreamOperator<Tuple2<String, Integer>> sumed = keyedStream.sum(1);



        sumed.writeToSocket("192.168.77.101", 22222, new SerializationSchema<Tuple2<String, Integer>>() {
            @Override
            public byte[] serialize(Tuple2<String, Integer> element) {
                return element.toString().getBytes();
            }
        });


      //  lines.writeAsCsv("D://a", FileSystem.WriteMode.OVERWRITE);
        env.execute();


    }
}
